package edu.gyc.hiwxm.aop;

import edu.gyc.hiwxm.exception.BookingException;
import edu.gyc.hiwxm.model.Booking;
import edu.gyc.hiwxm.service.BookingService;
import edu.gyc.hiwxm.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Aspect
@Component
@Slf4j
public class RobAop {
    @Autowired
    private BookingService bookingService;

    @Pointcut("execution(* edu.gyc.hiwxm.controller.BookingController.booking*(..))")
    public void rob() {

    }

    @Before("rob()")
    public void timeAuth(JoinPoint point) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        String id=request.getParameter("id"); //id对应抢单时的参数
        String loveid = request.getParameter("loveid"); //loveid对应预约时的参数
        Integer bookingid =null;
        if (id != null) {
            bookingid = Integer.valueOf(id);
        }

        if (loveid != null) {
            bookingid = Integer.valueOf(loveid);
        }

        Booking booking = bookingService.getById(bookingid);
        String bookingTimeString=booking.getWorkTime();
        Date bookingdate = DateUtils.convertString2Date("yyyy-MM-dd HH:mm", bookingTimeString);
        Date now = new Date();

        if (now.before(bookingdate)) {
            Long bookingtime=bookingdate.getTime();
            Long nowtime=now.getTime();
            //10分钟
            if(bookingtime-nowtime<=10*60*1000){
                throw new BookingException("距服务时间小于10分钟，无法预约和抢单，下次请早！");  //大于10分钟可以抢单
            }

        }else{
            throw new BookingException("时间已过，无法预约！");
        }

    }
}
